package cn.edu.hqu.cst.android.ls.webservice;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.SocketTimeoutException;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class ClientThread implements Runnable{
    //该线程负责处理的Socket
    private Socket s;
    private Handler handler;
    public Handler revHandler;
    //该线程所处理的Socket所对应的输入流
    BufferedReader br = null;
    OutputStream os =null;

    public ClientThread(Socket s , Handler handler)throws IOException{
        this.s = s;
        this.handler = handler;
        br = new BufferedReader(
                new InputStreamReader(s.getInputStream()));
    }

    public ClientThread(Handler handler) {
       this.handler= handler;
    }

    public void run(){
        try {
            s = new Socket("192.168.0.108", 40000);
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            os = s.getOutputStream();
            new Thread() {
                @Override
                public void run() {
                    String content = null;
                    try {
                        while ((content = br.readLine()) != null) {
                            Message msg = new Message();
                            msg.what = 0x123;
                            msg.obj = content;
                            handler.sendMessage(msg);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            Looper.prepare();
            revHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 0x345) {
                        try {
                            os.write((msg.obj.toString() + "\r\n").getBytes("utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            Looper.loop();
        }
        catch (SocketTimeoutException el) {
            System.out.println("网络连接超时！");
        }
        catch (Exception e){
            e.printStackTrace();}}}

